<template>
    <div>
        <div class="title">{{ route.query.id ? '编辑账号' : '新增账号' }}</div>
        <el-form :model="form" label-width="120px">
            <el-form-item label="AI配置">
                <el-checkbox v-model="form.checkAll" @change="handleCheckAllChange">全选
                </el-checkbox>
            </el-form-item>
            <el-form-item>
                <div style="display: flex;">
                    <el-tree ref="treeRef" v-for="(item, i) in test" :data="item" show-checkbox default-expand-all
                        node-key="code" highlight-current :props="{
                            children: 'child',
                            label: 'name',
                        }" :height="208" style="margin-right: 20px;" @check="fn" :default-checked-keys="defaultKes" />
                </div>
            </el-form-item>
            <el-form-item v-if="!route.query.id">
                <el-button @click="Back">上一步</el-button>
                <el-button type="primary" @click="onSubmit">下一步</el-button>
            </el-form-item>
            <el-form-item v-else="route.query.id">
                <el-button @click="toHome">取消</el-button>
                <el-button type="primary" @click="editSubmit">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useAddDataStore } from '../../store/useAddDataStore'
import { ElMessage } from 'element-plus'
import { getPermissions, getUseDetails, setUserDetails, setUserPolice } from '../../api/index'
const fromStore = useAddDataStore()
const treeRef = ref<any>(null)
const treeData = ref<any[]>([])
const defaultKes = ref<any[]>([])
const arrFlag = ref<string[]>([])
const editData = ref<any>({})

const fn = () => {
    treeData.value = []
    treeRef.value.forEach((element: any) => {
        element.getCheckedNodes().forEach((item: any) => {
            if (item.code) {
                treeData.value.push(item.code)
            }
        })
    });
    fromStore.permission_codes = treeData.value
    checkAllDetermine(treeData.value)
};

const checkAllDetermine = (bol: any[]) => {
    if (arrFlag.value.length === bol.length) {
        form.checkAll = true
    } else {
        form.checkAll = false
    }
}
const router = useRouter()
const route = useRoute()

const test = ref<any>([])
const form = reactive({
    checkAll: false,
})
const getData = async () => {
    let res = await getPermissions()
    test.value = res.data.data.map((item: any) => {
        return [item]
    })
    test.value.forEach((item: any) => {
        item.forEach((element: any) => {
            element.child.forEach((kes: any) => {
                arrFlag.value.push(kes.code)
            })
        })
    })
}

const editSubmit = async () => {
    //判断编辑的是商户还是公安

    if (treeData.value.length > 0) {
        let res = null
        if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {
            editData.value.permission_codes = treeData.value
            res = await setUserPolice(editData.value)
            console.log(res.data.code);
            if (res.data.code === 0) {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                router.push('/')
            } else {
                ElMessage.error('提交失败')
            }
        } else {
            editData.value.permission_codes = treeData.value
            res = await setUserDetails(editData.value)
            if (res.data.code === 0) {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                router.push('/')
            } else {
                ElMessage.error('提交失败')
            }
        }
    } else {
        ElMessage.error('至少选择一项AI配置')
    }



}
onMounted(async () => {
    await getData()
    if (fromStore.backFlag) {
        defaultKes.value = fromStore.permission_codes
        treeData.value = fromStore.permission_codes
        checkAllDetermine(defaultKes.value)
    }
    //判断是否为编辑
    if (route.query.id) {
        let res = (await getUseDetails({ id: route.query.id })).data.data
        if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {
            editData.value = {
                region_code: res.region_code,
                category: res.category,
                id: res.id,
                location: res.location,
                name: res.name,
                permission_codes: [],
                pid: res.pid,
                point: res.point,
                status: res.status,
                communities: res.communities,
                contact: {
                    phone: res.Administrator.phone,
                    real_name: res.Administrator.real_name,
                    remark: res.Administrator.remark,
                    username: res.Administrator.username,
                },

            }
        } else {
            editData.value = {
                category: res.category,
                community_id: res.community_id,
                contact: {
                    phone: res.Administrator.phone,
                    real_name: res.Administrator.real_name,
                    remark: res.Administrator.remark,
                    username: res.Administrator.username,
                },
                id: Number(route.query.id),
                location: res.location,
                region_code: res.region_code,
                name: res.name,
                permission_codes: [],
                pid: res.pid,
                point: res.point,
                remark: "",
                status: res.status
            }
        }
        defaultKes.value = res.PermissionCodes
        treeData.value = res.PermissionCodes
        checkAllDetermine(defaultKes.value)

    }

})
const toHome = () => {
    router.push('/')
}

const handleCheckAllChange = (val: boolean) => {
    defaultKes.value = []
    treeData.value = []
    if (val) {
        test.value.forEach((item: any) => {
            item.forEach((element: any) => {
                element.child.forEach((kes: any) => {
                    defaultKes.value.push(kes.code)
                    treeData.value.push(kes.code)
                })
            })
        })
        fromStore.permission_codes = treeData.value
    } else {
        treeRef.value.forEach((item: any) => {
            item.setCheckedKeys([])
        })
        fromStore.permission_codes = treeData.value
    }

}


const Back = () => {
    fromStore.backFlag = true
    router.push('/acctinfo')
}
const onSubmit = () => {
    if (treeData.value.length > 0) {
        fromStore.backFlag = false
        router.push('/acctediting')
    } else {
        ElMessage.error('至少选择一项AI配置')
    }


}
</script>
<style scoped lang='less'>
.title {
    height: 30px;
    line-height: 25px;
    border-bottom: 1px solid #ddd;
    margin-bottom: 10px;
}

/deep/.el-tree {
    background: transparent;
}
</style>